<!--
 * @Author: qwlbwm 18370818801qwl./
 * @Date: 2023-09-06 13:36:58
 * @LastEditors: qwlbwm 18370818801qwl./
 * @LastEditTime: 2023-09-27 14:40:17
 * @FilePath: \checc-business-module-web-kgpt-dev\src\views\examineManage\components\editAddStandardIndex.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <!-- 标准指标库的新增（包括中交和中咨） -->
  <div>
    <el-dialog
      v-model="dialogVisible"
      append-to-body
      :show-close="false"
      width="1100px"
      :title="opType === 'add' ? '新增配置项' : '编辑配置项'"
      :before-close="beforeClose"
      destroy-on-close
    >
      <div class="set-dialog-content itemAddDialog">
        <el-form
          :inline="true"
          :model="myForm"
          ref="ruleFormRef2"
          :rules="rules"
          label-position="top"
          label-width="120px"
        >
          <el-divider content-position="left">基本信息</el-divider>
          <el-form-item label="配置项名称" prop="name">
            <!-- 指标类型为类指标时从字典中选择名称 -->
            <el-input
              v-model="myForm.name"
              size="small"
              :disabled="pageDisabled"
              style="width: 240px"
              maxlength="20"

              show-word-limit clearable

            /><!--              oninput="value=value.replace(/[^\u4e00-\u9fa5]/g, '')"-->
          </el-form-item>
          <el-form-item
              label="配置项数据源一"
              prop="datasourceTwo"
          >
            <el-select
                v-model="myForm.datasourcefour"
                clearable
                style="width: 240px"
                size="small"
            >
              <el-option
                  v-for="item in datasourceOne_list"
                  :key="item.itemValue"
                  :label="item.itemText"
                  :value="item.itemValue"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="配置项数据源二"  >
            <el-cascader
              style="width: 240px"
              :show-all-levels="false"
              v-model="myForm.datasourcefive"
              :options="datasourcegz_list"
              size="small"
              :props="sourceCascaderpropsfive"
              clearable
              :popper-class="'hide'"
            />
          </el-form-item>
          <el-form-item label="配置项数据源三">
            <el-cascader
              style="width: 240px"
              :show-all-levels="false"
              v-model="myForm.datasource"
              :options="datasourceTwo_list"
              size="small"
              :props="sourceCascaderprops"
              clearable
              :popper-class="'hide'"
            />
          </el-form-item>
          <el-form-item label="父级项编号" prop="parentNumber">
            <el-cascader
              style="width: 240px"
              :show-all-levels="false"
              v-model="myForm.parentNumber"
              :options="composeItemData.composeItemSetList"
              size="small"
              :props="cascaderprops"
              :disabled="pageDisabled"
              clearable
            />
          </el-form-item>
          <el-form-item label="末位编号" prop="endNumber">
            <el-input
              v-model="myForm.endNumber"
              :disabled="pageDisabled"
              clearable
              size="small"
              style="width: 240px"
              :max="99"
              :min="0"
              maxlength="2"
              oninput="value=value.replace(/[^0-9]/g, '')"
            />
          </el-form-item>
          <el-form-item label="类型" prop="setType">
            <el-select
              v-model="myForm.setType"
              :disabled="pageDisabled"
              clearable
              style="width: 240px"
              size="small"
            >
              <el-option
                v-for="item in dict_setTypes"
                :key="item.itemValue"
                :label="item.itemText"
                :value="item.itemValue"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="配置项说明">
            <el-input
              v-model="myForm.intro"
              :disabled="pageDisabled"
              autosize
              size="small"
              style="width: 990px"
              maxlength="50"
              show-word-limit clearable

            /><!--     oninput="value=value.replace(/[^\u4e00-\u9fa5]/g, '')"         -->

          </el-form-item>
          <div v-if="myForm.setType === '2'" style="width: 100%">
            <el-divider content-position="left">系数规则</el-divider>
            <el-form-item label="标准系数" prop="standardFactor">
              <el-input
                v-model="myForm.standardFactor"
                :controls="false"
                style="width: 240px"
                :max="1"
                :min="0"
                :disabled="pageDisabled"
                maxlength="5"
                oninput="value=value.replace(/^0[0-9]|^[2-9]|^1[0-9]|^1\.|[^\d.]/g,'')"
              />
              <!-- <el-input v-model="myForm.standardFactor" type="" clearable style="width: 240px" size="small" /> -->
            </el-form-item>
            <el-row style="width: 100%">
              <el-col :span="12">
                <el-form-item label="参与方式系数">
                  <el-table border :data="dict_joinMethods">
                    <el-table-column prop="itemText" label="参与方式" width="200" />
                    <el-table-column prop="param" label="系数">
                      <template #default="scope">
<!--                        <el-input-number-->
                        <el-input
                          v-model="myForm.joinFactorObj['factor_' + scope.row.itemValue]"
                          :controls="false"
                          :max="1"
                          :min="0"
                          :disabled="pageDisabled"
                          maxlength="5"
                          oninput="value=value.replace(/^0[0-9]|^[2-9]|^1[0-9]|^1\.|[^\d.]/g,'')"
                        />
                      </template>
                    </el-table-column>
                  </el-table>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="排名系数">
                  <el-table border :data="rankFactor_table">
                    <el-table-column prop="name" label="排名" width="200">
                      <template #default="scope">
                        <el-select v-model="scope.row.rank" :disabled="pageDisabled" size="small">
                          <el-option
                            v-for="item in dict_ranklist"
                            :key="item.itemValue"
                            :label="item.itemText"
                            :value="item.itemValue"
                          >
                          </el-option>
                        </el-select>
                        <span v-if="scope.$index === rankFactor_table.length - 1">或以后</span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="param" label="系数">
                      <template #default="scope">
<!--                        <el-input-number-->
                        <el-input
                          v-model="scope.row.fator"
                          :disabled="pageDisabled"
                          :controls="false"
                          :max="1"
                          :min="0"
                          maxlength="5"
                          oninput="value=value.replace(/^0[0-9]|^[2-9]|^1[0-9]|^1\.|[^\d.]/g,'')"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="100">
                      <template #default="scope">
                        <el-button
                          type="danger"
                          v-if="scope.$index !== 0"
                          @click="deleteRankTable(scope)"
                          :disabled="pageDisabled"
                          >删除</el-button
                        >
                      </template>
                    </el-table-column>
                    <template #append>
                      <div class="appendFooter" style="height: 49px">
                        <div class="td" style="width: 200px;">
                          <el-button type="primary"
                                     :disabled="pageDisabled"
                                     @click="insertTankTable">增加</el-button>
                        </div>
                        <div class="td" style="width: 199px"></div>
                        <div class="td" style="flex: 1"></div>
                      </div>
                    </template>
                  </el-table>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="confirm()"> 保存 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import {
  computed,
  ref,
  defineComponent,
  reactive,
  watch,
  toRefs,
  nextTick,
  getCurrentInstance,
} from 'vue'
import { dataDictionary } from '@/api/dict'
import { ElMessage } from 'element-plus'
import * as api from '../../../api/examineManage'
import pubFc from '../../../utils'
import { filterDepthTree } from '@/utils/utils'
import { cloneDeep } from 'lodash'
export default defineComponent({
  components: {},
  emits: {
    'update:visible': null,
    refresh: null,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    standardType: {
      type: String, //1中交还是2中资
      default: '1',
    },
    opType: {
      type: String,
      default: 'add',
    },
    editForm: {
      type: Object,
    },
    indexHandleData: {
      //当前操作的指标数据
      type: Object,
    },
    composeItemData: {
      //当前操作的评分管理数据
      type: Object,
    },
    propDict: {
      //传递过来的字典
      type: Object,
    },
    insertApi: {
      type: String,
    },
    updateApi: {
      type: String,
    },
    apiPackage: {
      //全部接口打包必须包含{detail:'',score:'',insert:'',update:'',deletel:''}
      type: Object,
      default: () => {
        return {
          detail: '', //查询详情接口
          score: '', //更新计分接口
          insert: '', //新增配置项接口
          update: '', //更新配置项接口
          delete: '', //删除配置项接口
        }
      },
      required: true, // 必传项
    },
    pageDisabled: {
      type: Boolean,
      default: false,
    },
  },
  setup(props, { emit }) {
    const { propDict } = toRefs(props)
    const dialogVisible = computed(() => {
      return props.visible
    })
    const ruleFormRef2 = ref<any>()
    const rules = reactive<any>({
      name: [{ required: true, message: '请填写配置项名称', trigger: 'blur' }],
      endNumber: [{ required: true, message: '请填写末位编号', trigger: 'blur' }],
      setType: [{ required: true, message: '请选择类型', trigger: 'blur' }],
      // datasource: [{ required: true, message: '请选择数据源', trigger: 'change' }],
      standardFactor: [{ required: true, message: '请填写标准系数', trigger: 'blur' }],
    })
    const state = reactive<any>({
      //整体数据带dict全是字典查询
      cascaderprops: {
        checkStrictly: true,
        value: 'number',
        label: 'number',
        emitPath: false,
      },
      sourceCascaderpropsfive: { value: 'itemValue', label: 'itemText',checkStrictly: false,expandTrigger:'click'},
      sourceCascaderprops: { value: 'itemValue', label: 'itemText',checkStrictly: false,expandTrigger:'click'},
      sourceCascaderprops2: { value: 'itemValue', label: 'itemText', checkStrictly: true },
      datasourceOne_list: [],
      datasourceTwo_list: [],
      datasourceThree_list: [],
      datasourcegz_list: [],
      dict_joinMethods: propDict?.value?.dict_joinMethods,
      dict_ranklist: propDict?.value?.dict_ranklist,
      dict_setTypes: [],
      itemSet_list: [],
      rankFactor_table: [],
      datasourceModel: 1, //配置项数据源模式
    })

    const myForm: any = reactive({
      name: '',
      endNumber: '',
      parentNumber: '',
      intro: '',
      datasourceOne: '',
      datasourceTwo: '',
      datasourceThree: '',
      datasource: '',
      datasourcefour: [],
      datasourcefive: [],
      setType: '',
      standardFactor: null,
      joinFactorObj: {},
      joinFactor: {},
      rankFactor: {},
    })

    const beforeClose = () => {
      cancel()
    }
    watch(
      () => props.visible,
      (newval) => {
        if (newval) {
          getDictDatas()
          nextTick(() => {
            //初始绑定需在form完成初始化
            ruleFormRef2.value?.resetFields()
            if (props.opType === 'edit') {
              pubFc.ojectCopyObj(myForm, props.editForm)
              myForm.joinFactorObj = {}
              for (let i = 0; i < state.dict_joinMethods.length; i++) {
                myForm.joinFactorObj['factor_' + state.dict_joinMethods[i].itemValue] = undefined
              }
              myForm.datasourcefour=myForm.datasourceOne;
              myForm.datasourcefive=myForm.datasourceTwo ? myForm.datasourceTwo.split(',') : null;
              myForm.datasource = myForm.datasourceThree ? myForm.datasourceThree.split(',') : null;
              state.rankFactor_table = []
              if (myForm.rankFactor) {
                for (const key in myForm.rankFactor) {
                  state.rankFactor_table.push({
                    rank: key,
                    fator: myForm.rankFactor[key],
                  })
                }
              } else {
                myForm.rankFactor = {}
                state.rankFactor_table = [
                  {
                    rank: '1',
                    fator: undefined,
                  },
                ]
              }
              if (myForm.joinFactor) {
                for (const key in myForm.joinFactor) {
                  myForm.joinFactorObj['factor_' + key] = myForm.joinFactor[key]
                }
              } else {
                myForm.joinFactor = {}
                for (const key in myForm.joinFactorObj) {
                  myForm.joinFactorObj[key] = undefined
                }
              }
            } else {
              resetForm()
            }
          })
        } else resetForm()
      }
    )
    const resetForm = () => {
      for (const key in myForm) {
        switch (key) {
          case 'datasourcefour':
            myForm[key] = [];
            break
          case 'datasourcefive':
            myForm[key] = [];
            break
          case 'joinFactorObj':
            myForm[key] = {};
            break
          case 'joinFactor':
            myForm[key] = {};
            break
          case 'rankFactor':
            myForm[key] = {};
            break
          default:
            myForm[key] = '';
            break
        }
      }
      //清除那些resetFields无法清除的字段
      myForm.standardFactor = undefined
      state.rankFactor_table = [
        {
          rank: '1',
          fator: undefined,
        },
      ]
      if (myForm.joinFactorObj) {
        for (const key in myForm.joinFactorObj) {
          myForm.joinFactorObj[key] = undefined
        }
      }
    }
    const dataSourceChange1 = (value) => {
      console.log(state.datasourceOne_list)
      myForm.datasourceTwo = ''
      let t = state.datasourceOne_list.find((it) => it.itemValue === value).children
      console.log(state.datasourceOne_list)
      if (t.children && t.children.length > 1) {
        state.datasourceTwo_list = t.children
      } else {
        state.datasourceTwo_list = []
      }
    }
    const dataSourceChange2 = (value) => {
      myForm.datasourceThree = ''
      let t = state.datasourceTwo_list.find((it) => it.itemValue === value)
      if (t.children && t.children.length > 1) {
        state.datasourceThree_list = t.children
      } else {
        state.datasourceThree_list = []
      }
    }
    const cancel = () => {
      emit('update:visible', false)
      myForm.intro = ''
    }
    const resetJoinFactor = (params) => {
      for (const key in params.joinFactorObj) {
        let key2 = key.split('_')[1]
        params.joinFactor[key2 as any] = ''
      }
    }
    const confirm = () => {
      ruleFormRef2.value.validate((valid) => {
        if (valid) {
          let params: any = {
              ...myForm,
            },
            apiName = ''
          if (params.setType === '2') {
            params.rankFactor = {}
            state.rankFactor_table.map((item) => {
              if (item.rank) {
                params.rankFactor[item.rank] = item.fator || ''
              }
            })

            for (let key in params.joinFactorObj) {
              let key2 = key.split('_')[1]
              params.joinFactor[key2] = params.joinFactorObj[key]
            }
          } else {
            params.joinFactorObj = null
            params.joinFactor = null
            params.standardFactor = null
            params.rankFactor = null
          }
          if (props.opType === 'add') {
            params.composeItemId = props.composeItemData?.id
            // apiName = 'insertItemSetRequest'
            apiName = props.apiPackage.insert
          } else {
            params.id = props.editForm?.id
            // apiName = 'updateItemSetRequest'
            apiName = props.apiPackage.update
          }
          console.log('开始调用保存接口-----------：', params);
          params.datasourceOne = (myForm.datasourcefour.length==0)?'':myForm.datasourcefour;
          // params.datasourceOne = '';
          params.datasourceTwo = Array.isArray(myForm.datasourcefive) ? myForm.datasourcefive.join(',') : '';
          params.datasourceThree = Array.isArray(myForm.datasource) ? myForm.datasource.join(',') : '';
          Reflect.deleteProperty(params, 'datasource');
          Reflect.deleteProperty(params, 'datasourcefour');
          Reflect.deleteProperty(params, 'datasourcefive');
          api[apiName](params).then((res) => {
            if (res.data.success) {
              ElMessage({
                message: props.opType === 'edit' ? '成功修改' : '成功创建',
                type: 'success',
              })
              cancel()
              emit('refresh')
            }
          })
        }
      })
      //确定新增或修改
    }

    const getDictDatas = () => {
      let key = props.indexHandleData?.scoreSource
      let dict_key = ['KHGL_COMPOSE_SET_TYPE_CODE']
      let dictId_corres = {
        '01': 'KJSL_GD_LEVEL',
        '02': 'KJSL_INNOVATE_PLATFORM_LEVEL',
        '03': 'KJSL_GD_LEVEL',
        '04': 'KJSL_GJ_LEVEL',
        '05': 'KJSL_LJ_LEVEL',
        '06': 'KJSL_CX_LEVEL',
        '07': 'KHGL_INDEX_SET_ZLRZ_CODE',
        '08': 'KHGL_INDEX_SET_ZZLW_CODE',
        '09': 'KJSL_PROJECT_LEVEL_CATEGORY1',
        '10': 'KJSL_PROJECT_LEVEL_CATEGORY',
        '11': 'KHGL_KJSL_HJJB',
        '12': 'KJSL_EVALUATION_LEVEL_EVALUATION_SUBJECT',
      }
      // 当key为03\13\14需要额外的判断字典取值，因为不同的tab需要不同的字典
      const tabCode = props.composeItemData?.composeItem || '';
      let dictKey: string = dictId_corres[key];
      if (key == '02') {
        //02的还需要多查一个字典
        dict_key.push('KJSL_INNOVATE_ZY_LEVEL')
      } else if (key === '03') {
        if (tabCode === 'A0006') dictKey = 'KJSL_GD_LEVEL1'
        else if (tabCode === 'A0007') dictKey = 'KJSL_GD_LEVEL2'
        else dictKey = 'KJSL_GD_LEVEL'
      } else if (key === '13') {
        // tabCode === 'A0017'
        if (tabCode === 'A0016') dictKey = 'KJSL_PROJECT_LEVEL_CATEGORY1'
        else dictKey = 'KJSL_PROJECT_LEVEL_CATEGORY'
      } else if (key === '14') {
        // tabCode === 'A0019'
        if (tabCode === 'A0018') dictKey = 'KJSL_STANDARD_LEVEL_CATEGORY'
        else dictKey = 'KJSL_CONSTRUCTION_METHOD_LEVEL_CATEGORY'
      }
      dict_key.push(dictKey)
      dataDictionary(dict_key).then((res) => {
        let response = res.data.data

        state.dict_setTypes = response['KHGL_COMPOSE_SET_TYPE_CODE']
        if (key == '02') {
          //02的还需要多查一个字典
          let a = response[dictKey];
          a.map((item) => {
            item.children = []
            item.children = response['KJSL_INNOVATE_ZY_LEVEL'] || []
          })
          state.datasourceOne_list = a
        } else {
          const date = response[dictKey] || [];
          state.datasourceOne_list = date.slice();
          state.datasourcegz_list = date.slice().filter(t => t.children?.length).map(t => {
            const item = cloneDeep(t);
            item.children.forEach((row: Record<string, any>) => {
              Reflect.deleteProperty(row, 'children');
            })
            return item
          })
          state.datasourceTwo_list = filterDepthTree(date, 3);
        }
         if (key == '05') {
          state.datasourceOne_list.map(item=>{
            if(item.children){
              item.children.map(item2=>{
                item2.children=null;
              })
            }
          })
         }else if(key == '04'){
          state.datasourceOne_list.map(item=>{
            item.children=null
          })
         }
      })

    }
    const getLevelChilren=()=>{  //获取第x级children

    }
    const deleteRankTable = (scope) => {
      //删除排名系数列表

      state.rankFactor_table.splice(scope.$index, 1)
    }
    const insertTankTable = () => {
      state.rankFactor_table.push({
        rank: '',
        fator: '',
      })
    }
    return {
      ...toRefs(state),
      myForm,
      dialogVisible,
      rules,
      ruleFormRef2,
      dataSourceChange1,
      dataSourceChange2,
      deleteRankTable,
      insertTankTable,
      beforeClose,
      cancel,
      confirm,
    }
  },
})
</script>
<style lang="scss" scoped>
.set-dialog-content {
  padding: 20px;
  .qwl-table {
    .t-header {
      background: #eef1f6;
    }
    .qwl-table-row {
      display: flex;
      .row-tb {
        min-width: 100px;
        padding: 8px;
      }
    }
  }
}
</style>
<style lang="scss">
.itemDataSource-qwl {
  .el-cascader-panel .el-cascader-menu:first-child .el-radio {
    display: none !important;
  }
}
</style>
